package com.examples.springboot.jpa.gui.department;

import java.util.ArrayList;
import java.util.List;

import javax.swing.table.AbstractTableModel;

import com.examples.springboot.jpa.pojos.DepartmentDto;
import com.examples.springboot.jpa.pojos.EmployeeDto;
import com.examples.springboot.jpa.resources.EmployeeResource;

/**
 * A custom table model for the table of ClimberDto. 
 *
 */
@SuppressWarnings("serial")
public class EmployeeTableModel extends AbstractTableModel {
	private String[] columnNames = {"No.", "Name", "Department", "PhoneNumbers"};
	private final List<EmployeeDto> listEmployee = new ArrayList<>();

	private final EmployeeResource resource;
	public EmployeeTableModel(EmployeeResource resource) {
	  this.resource=resource;
	}

	public void loadData() {
    setData(resource.getAll());
  }

	public void setData(List<EmployeeDto> listEmployee){
	  if(listEmployee.isEmpty())
      this.listEmployee.clear();
	  else
	  for (EmployeeDto employeeDto : listEmployee) {
      this.listEmployee.add(employeeDto);
    }

    fireTableDataChanged();
	}

	@Override
	public int getColumnCount() {
		return columnNames.length;
	}

  public String getColumnName(int column) {
    return columnNames[column];
  }

  public Class<?> getColumnClass(int column) {
    return getValueAt(0, column).getClass();
  }

	@Override
	public int getRowCount() {
		return listEmployee.size();
	}

	@Override
	public void setValueAt(Object value, int rowIndex, int columnIndex) {
	  EmployeeDto employee = listEmployee.get(rowIndex);

		switch (columnIndex) {
		case 1:
		  employee.setName((String)value);
			break;
		case 2:
      employee.setDepartment((DepartmentDto) value);
			break;
		case 3:
      employee.setPhoneNumber((String)value);
      break;
		}		
	}

	@Override
	public Object getValueAt(int rowIndex, int columnIndex) {
		Object returnValue = null;
		EmployeeDto employee = listEmployee.get(rowIndex);
		
		switch (columnIndex) {
		case 0:
				returnValue = employee.getId();
			break;
		case 1:
				returnValue = employee.getName();
			break;
		case 2:
				returnValue = employee.getDepartment();
			break;
		case 3:
      returnValue = employee.getPhoneNumber();
    break;
		}
		
		return returnValue;
	}

  public boolean isCellEditable(int rowIndex, int columnIndex) {
    return columnIndex == 2;
  }
}
